package com.ykdl.member.kid.util;

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.weibo.net.AccessToken;
import com.weibo.net.AsyncWeiboRunner;
import com.weibo.net.DialogError;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;
import com.ykdl.member.base.QLog;
/**
 * 微博分享的工具
 * @see
 * @since 1.0
 */
public class WeiBoUtil {
	private static final String URL_ACTIVITY_CALLBACK = "http://www.wxxr.com.cn";
	// 设置appkey及appsecret，如何获取新浪微博appkey和appsecret请另外查询相关信息，此处不作介绍
	private static final String CONSUMER_KEY = "2347116809";//
	private static final String CONSUMER_SECRET = "78306897820bdaf5c45b340faead534b";// 
    private static	WeiBoUtil instance;
    public static final String WEIBO_TEXT="weibo_text";
    public static final String WEIBO_PIC="weibo_pic";
    private Context mContext;
    
    private static String  temptoken;
    private static String  tempexpires_in;
    
	private WeiBoUtil(){
		
	}
	
	public static WeiBoUtil getInstance(){
		if(instance==null){
			instance=new WeiBoUtil();
		}
		return instance;		
	}
	
	com.weibo.net.AsyncWeiboRunner.RequestListener weibosendListner=new com.weibo.net.AsyncWeiboRunner.RequestListener(){
		@Override
		public void onComplete(String response) {
			Toast.makeText(mContext, "微博分享成功", Toast.LENGTH_SHORT).show();
			QLog.debug("Weibo onComplete : "+response);
			
		}

		@Override
		public void onIOException(IOException e) {
			Toast.makeText(mContext, "微博分享失败", Toast.LENGTH_SHORT).show();
			QLog.debug("Weibo onIOException : "+e.toString());
			
		}

		@Override
		public void onError(WeiboException e) {
			Toast.makeText(mContext, "微博分享失败", Toast.LENGTH_SHORT).show();
			QLog.debug("Weibo WeiboException : "+e.toString());
			
		}
		
		
	};
	
	
	public  void shareWeibo(Activity context,Class<?>backActivity,Bundle param,boolean sendDirect) {
		mContext=context;
		if(temptoken!=null){
			AccessToken accessToken = new AccessToken(temptoken, CONSUMER_SECRET);
			accessToken.setExpiresIn(tempexpires_in);			
			Weibo weibo=com.weibo.net.Weibo.getInstance();
			weibo.setAccessToken(accessToken);
			if (sendDirect){			
				try{					
				upload(Weibo.getInstance(),mContext, Weibo.getAppKey(),  Weibo.getInstance().getAccessToken().getToken(),Weibo.getInstance().getAccessToken().getSecret(),param.getString(WEIBO_PIC),param.getString(WEIBO_TEXT), "", "");
				
				}catch(Exception ee){
					QLog.debug("AuthDialogListener send wei bo err", ee.toString());
				}	

			}
		
			if(backActivity!=null){
				Intent intent = new Intent();
				intent.setClass(mContext, backActivity);
				if(param!=null){
					intent.putExtras(param);
				}
				mContext.startActivity(intent);				   			
			}	
			
			
		}else{
		
		
		Weibo weibo = Weibo.getInstance();
		weibo.setupConsumerConfig(CONSUMER_KEY, CONSUMER_SECRET);
		// Oauth2.0
		// 隐式授权认证方式
		weibo.setRedirectUrl(URL_ACTIVITY_CALLBACK);// 此处回调页内容应该替换为与appkey对应的应用回调页
		// 对应的应用回调页可在开发者登陆新浪微博开发平台之后，
		// 进入我的应用--应用详情--应用信息--高级信息--授权设置--应用回调页进行设置和查看，
		// 应用回调页不可为空
		weibo.authorize(context, new AuthDialogListener(context,backActivity,param,sendDirect));
		}
	}

	class AuthDialogListener implements WeiboDialogListener {
		Activity mContext;
		Class<?> mBack;
		Bundle mParam;
		boolean sendDirect;
		boolean first=false;
		AuthDialogListener(Activity context, Class<?> back,Bundle parame,boolean psendDirect) {
			mContext = context;
			mBack = back;
			mParam=parame;
			sendDirect=psendDirect;

		}
		@Override
		public void onComplete(Bundle values) {
			
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			temptoken=token;
			tempexpires_in=expires_in;
			// mToken.setText("access_token : " + token + "  expires_in: "
			// + expires_in);
			AccessToken accessToken = new AccessToken(token, CONSUMER_SECRET);
			accessToken.setExpiresIn(expires_in);
			
			Weibo weibo=com.weibo.net.Weibo.getInstance();
			weibo.setAccessToken(accessToken);

			if (sendDirect){			
				try{					
				upload(Weibo.getInstance(),mContext, Weibo.getAppKey(),  Weibo.getInstance().getAccessToken().getToken(),Weibo.getInstance().getAccessToken().getSecret(),mParam.getString(WEIBO_PIC),mParam.getString(WEIBO_TEXT), "", "");
				
				}catch(Exception ee){
					QLog.debug("AuthDialogListener send wei bo err", ee.toString());
				}			

			}
		
			if(mBack!=null){
				Intent intent = new Intent();
				intent.setClass(mContext, mBack);
				if(mParam!=null){
					intent.putExtras(mParam);
				}
				mContext.startActivity(intent);				   			
			}			
			
			
		}

		@Override
		public void onError(DialogError e) {
			QLog.debug("Weibo Auth error : ", e.getMessage());
		}

		@Override
		public void onCancel() {
			QLog.debug("Weibo onCancel : ");
		}

		@Override
		public void onWeiboException(WeiboException e) {
		//	Toast.makeText(mContext, "微博分享失败"+e.getMessage(), Toast.LENGTH_SHORT).show();
			QLog.debug("Weibo onCancel ", "onWeiboException : " + e.getMessage());
		}			
		}

	/**
	 * 
	 * @param weibo
	 * @param context
	 * @param source   
	 * @param key
	 * @param secret
	 * @param file 附件 使用upload 接口
	 * @param status  文字，使用 update 接口
	 * @param lon   精度
	 * @param lat  纬度
	 * @return
	 * @throws WeiboException
	 */
     //             upload( context, Weibo.getAppKey(), this.mPicPath, this.mContent, "", "");
	 private String upload(Weibo weibo,Context context,String source,String key,String secret, String file, String status, String lon,
	            String lat) throws WeiboException {
		 boolean upload=false;
		 AccessToken ac= new AccessToken(key,secret);
		 weibo.setAccessToken(ac);
	        WeiboParameters bundle = new WeiboParameters();
	        bundle.add("source", source);
	        if (!(TextUtils.isEmpty(file)||"NULL".equals(file)||"null".equals(file))) {
	        	upload=true;
	            bundle.add("pic", file);
	        }
	        if (!TextUtils.isEmpty(status)) {
	        	  bundle.add("status", status);
	        }
	        
	     
	        if (!TextUtils.isEmpty(lon)) {
	            bundle.add("lon", lon);
	        }
	        if (!TextUtils.isEmpty(lat)) {
	            bundle.add("lat", lat);
	        }
	        String rlt = "";
	        String url = Weibo.SERVER + "statuses/update.json";
	        if(upload){
	        	url = Weibo.SERVER + "statuses/upload.json";
	        }
	        		
	        AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
	        weiboRunner.request(context, url, bundle, Utility.HTTPMETHOD_POST, weibosendListner);

	        return rlt;
	    } 
	
	 
	 
}
